package com.psbc.redis_study.controller;

import com.psbc.redis_study.model.VideoCardDo;
import com.psbc.redis_study.service.VideoCardService;
import com.psbc.redis_study.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/video")
public class VideoCardController {
    @Autowired
    private VideoCardService videoCardService;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String VIDEO_CARD_CACHE_KEY = "service:card:key";

    /**
     * 查询热点数据时走缓存
     * @return
     */
    @GetMapping("/list_cache")
    public JsonData listCardCache(){
        Object cacheObj = redisTemplate.opsForValue().get(VIDEO_CARD_CACHE_KEY);
        if (cacheObj != null){
            List<VideoCardDo> list = (List<VideoCardDo>) cacheObj;
            return JsonData.buildSuccess(list);
        }else {
            List<VideoCardDo> cardDoList = videoCardService.list();
            redisTemplate.opsForValue().set(VIDEO_CARD_CACHE_KEY,cardDoList,10, TimeUnit.MINUTES);
            return JsonData.buildSuccess(cardDoList);
        }
    }

    /**
     * 查询热点数据时不走缓存
     * @return
     */
    @GetMapping("/list_nocache")
    public JsonData listCardNoCache(){
        List<VideoCardDo> cardDoList = videoCardService.list();
        return JsonData.buildSuccess(cardDoList);
    }
}
